package com.puboot.component;

import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
 * @author Leonidax
 * @date 2024/10/10 16:37
 * @description ComicCookeLocaleResolver
 */
public class ComicCookeLocaleResolver extends CookieLocaleResolver {
    public static Locale defaultLanguage = new Locale("en","");

    // 定义支持的语言列表：中文、英文、法语、西班牙语、印地语、阿拉伯语、孟加拉语、俄语、印尼语、葡萄牙语
    private static final List<Locale> SUPPORTED_LOCALES = Arrays.asList(
            defaultLanguage,
            new Locale("fr",""),
            new Locale("es",""),
            new Locale("hi",""),
            new Locale("ar",""),
            new Locale("bn",""),
            new Locale("ru",""),
            new Locale("id",""),
            new Locale("pt","")

    );
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getParameter("lang");
        Locale locale = (lang != null && !lang.isEmpty()) ? new Locale(lang) : defaultLanguage;

        // 检查传入的语言是否支持，不支持则回退到默认语言
        if (!SUPPORTED_LOCALES.contains(locale)) {
            locale = defaultLanguage;
        }

        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        // 检查传入的语言是否支持，不支持则回退到默认语言
        if (!SUPPORTED_LOCALES.contains(locale)) {
            locale = defaultLanguage;
        }
        super.setLocale(request, response, locale);
    }
}
